<template>
  <ErrorUnknown v-if="error"></ErrorUnknown>
  <Loading v-else-if="loading"></Loading>
  <Viewer :router="viewerRouter" @back="onBack"></Viewer>
</template>

<script setup>
import { computed, defineAsyncComponent, ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useAppStore } from '@/store/app'
import { useChatPanelStore } from '@/store/chat-panel'
import ErrorUnknown from '@/components/common/ErrorUnknown.vue'
import Loading from '@/components/common/Loading.vue'
import { useInfinite } from '@/compositions/request/infinite'
import { useDesktopViewerRouter } from '@/compositions/viewer/router/desktopViewerRouter'
import { useMobileViewerRouter } from '@/compositions/viewer/router/mobileViewerRouter'
import API from '@/http'

const props = defineProps({
  ids: { type: String }, // 逗號分隔帖子id
  creator: { type: Object, validator: (v) => !!(v.aff && v.username) },
  active: { type: Boolean, default: false },
  isNotify: { type: Boolean, default: false },
  isProduct: { type: Boolean, default: false },
})
const emits = defineEmits(['back'])

const Viewer = defineAsyncComponent(() => import('@/components/viewer/Viewer.vue'))

const appStore = useAppStore()
const { isDesktop } = storeToRefs(appStore)

const viewerRouter = isDesktop.value
  ? useDesktopViewerRouter('desktop-message')
  : useMobileViewerRouter('mobile-message')
const { active: viewerActive, setFromMainViewer, toIndexedMainViewer, setFromCreator, revertPath } = viewerRouter

const chatPanelStore = useChatPanelStore()
const { open: openChatPanel } = chatPanelStore
const openChat = computed(() => props.isNotify && !props.isProduct)

function onBack() {
  revertPath()
  emits('back')
}

const loading = ref(true)
const error = ref(false)

let firstMediaItem

watch(
  [() => props.ids, () => props.active, () => props.creator],
  ([ids, active, creator], [prevIds, prevActive, prevCreator], onCleanup) => {
    if ([ids, creator].every((v) => !v) || [ids, creator].every((v) => !!v)) {
      loading.value = true
      error.value = false
      firstMediaItem = undefined
      viewerActive.value = false
      return
    }

    viewerActive.value = active

    if (ids && !creator) loadFeed({ ids, prevIds, active }, onCleanup)
    if (creator && !ids) loadCreator({ creator, prevCreator, active })
  },
  { immediate: true },
)

function loadCreator({ creator, prevCreator }) {
  if (!creator || creator.aff === prevCreator?.aff) return

  loading.value = true
  error.value = false

  try {
    setFromCreator(creator.aff, creator.username)
  } catch (e) {
    loading.value = false
    error.value = true
    console.warn(e)
  } finally {
    loading.value = false
  }
}

function loadFeed({ ids, prevIds, active }, onCleanup) {
  // 帖子沒改變
  if (ids === prevIds) {
    if (active) {
      toIndexedMainViewer(0)
      if (openChat.value && firstMediaItem) {
        openChatPanel(firstMediaItem)
      }
    }
    return
  }

  let cleanup = false
  onCleanup(() => (cleanup = true))

  // 載入開始
  loading.value = true
  error.value = false

  try {
    setFromMainViewer({
      video: useInfinite({
        request: API.Media.getPostList,
        params: { id: ids },
        onInit: (dataList) => {
          if (!cleanup) {
            firstMediaItem = dataList[0]
            if (openChat.value && firstMediaItem) {
              openChatPanel(firstMediaItem)
            }
            loading.value = false
          }
        },
      }),
    })
  } catch (e) {
    loading.value = false
    error.value = true
    console.warn(e)
  }
}

function transformer(item) {
  item.need_buy = false
  item.need_subscribe = false
  item.can_play = true
  return item
}
</script>
